package com.shoplook2025.category.api.api;

import com.shoplook2025.category.model.Category;
import com.shoplook2025.category.service.CategoryService;
import com.shoplook2025.core.utils.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yan
 * @date 2025/8/26
 */
@RestController
@RequestMapping(value = "/api/category",produces = MediaType.APPLICATION_JSON_VALUE)
public class CategoryApi {
    private CategoryService categoryService;
    @Autowired
    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @GetMapping
    public ResponseEntity<JsonResult<?>> findAll(Category category){
        List<Category> categories =this.categoryService.findAll(category);
        return ResponseEntity.ok(JsonResult.success(categories));
    }

    @GetMapping("/all")
    public ResponseEntity<JsonResult<?>> findAll() {
        List<Category> categories =this.categoryService.findAll();
        return ResponseEntity.ok(JsonResult.success(categories));
    }

    @GetMapping("/tree")
    public ResponseEntity<JsonResult<?>> findTree() {
        List<Category> categories =this.categoryService.findTree();
        return ResponseEntity.ok(JsonResult.success(categories));
    }

    @GetMapping("/id/{id}")
    public ResponseEntity<JsonResult<?>> findById(@PathVariable Integer id){
        Category category =this.categoryService.findById(id);
        if (category==null){
            return ResponseEntity.ok(JsonResult.fail("未找到该分类"));
        }else {
            return ResponseEntity.ok(JsonResult.success(category));
        }
    }


    @PostMapping
    public ResponseEntity<JsonResult<?>> save(@RequestBody Category category){
        boolean success = this.categoryService.save(category);
        if (success){
            return ResponseEntity.ok(JsonResult.success());
        }else {
            return ResponseEntity.ok(JsonResult.fail("保存失败"));
        }
    }

    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@RequestBody Category cat) {
        boolean success = this.categoryService.update(cat);
        if (success) {
            return ResponseEntity.ok(JsonResult.success());
        } else {
            return ResponseEntity.ok(JsonResult.fail("修改分类失败"));
        }
    }


    @DeleteMapping
    public ResponseEntity<JsonResult<?>> deleteByIds(@RequestBody Integer[] ids){
        int count=0;
        for(Integer id:ids){
            count+=this.categoryService.deleteById(id);
        }
        if(count==0){
            return ResponseEntity.ok(JsonResult.fail("删除失败"));
        }else {
            return ResponseEntity.ok(JsonResult.success(count));
        }
    }

}
